#!/usr/bin/env bash
# Copyright (c) 2018, the Dart project authors.  Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.

# Script for generating bytecode in a kernel file using Dart 2 pipeline and
# interpreting the resulting bytecode.

# Usage
# pkg/vm/tool/test_bytecode ~/foo.dart

set -e

# Pick the architecture and mode to test.
BUILD_FLAGS="-m release -a x64"
BUILD_SUBDIR="ReleaseX64"

function follow_links() {
  file="$1"
  while [ -h "$file" ]; do
    # On Mac OS, readlink -f doesn't work.
    file="$(readlink "$file")"
  done
  echo "$file"
}

# Unlike $0, $BASH_SOURCE points to the absolute path of this file.
PROG_NAME="$(follow_links "$BASH_SOURCE")"

# Handle the case where dart-sdk/bin has been symlinked to.
CUR_DIR="$(cd "${PROG_NAME%/*}" ; pwd -P)"

SDK_DIR="$CUR_DIR/../../.."
BUILD_DIR="$SDK_DIR/out/$BUILD_SUBDIR"

# Regenerate vm_platform_strong.dill to contain bytecode if needed:
# $SDK_DIR/tools/gn.py $BUILD_FLAGS --bytecode
# $SDK_DIR/tools/build.py $BUILD_FLAGS runtime

# Generate dill file containing bytecode for input dart source.
$CUR_DIR/gen_kernel --platform $BUILD_DIR/vm_platform_strong.dill \
  --gen-bytecode $@ -o $BUILD_DIR/test_bytecode.dill

# Dump bytecode in generated vm_platform_strong.dill file to platform.txt.
# $BUILD_DIR/dart $SDK_DIR/pkg/vm/bin/dump_kernel.dart \
#   $BUILD_DIR/vm_platform_strong.dill $BUILD_DIR/platform.txt

# Dump bytecode in generated test_bytecode.dill file to test_bytecode.txt.
# $BUILD_DIR/dart $SDK_DIR/pkg/vm/bin/dump_kernel.dart \
#   $BUILD_DIR/test_bytecode.dill $BUILD_DIR/test_bytecode.txt

# Required flag.
DART_VM_FLAGS="--enable-interpreter $DART_VM_FLAGS"

# Optional flags examples. Uncomment as needed.
# DART_VM_FLAGS="--compilation-counter-threshold=-1 $DART_VM_FLAGS"
# DART_VM_FLAGS="--force-log-flush --isolate-log-filter=\"\" $DART_VM_FLAGS"
# DART_VM_FLAGS="--dump-kernel-bytecode $DART_VM_FLAGS"
# DART_VM_FLAGS="--trace-interpreter-after=0 $DART_VM_FLAGS"

# Execute dill file.
exec $BUILD_DIR/dart $DART_VM_FLAGS $BUILD_DIR/test_bytecode.dill

